﻿function drawContentTypes(contentTypes) {
    var className = "uneven";
    contentTypes.each(function () {
        jQuery("#contentTypes")
            .append(jQuery("<li class=" + className + ">")
            .append(jQuery("<span>" + jQuery(this).attr("name") + "</span>"))
            .append("<span class=\"updateColumn\"><a id=\"" + jQuery(this).attr("id") + "\" href=\"javascript:updateContentType('" + jQuery(this).attr("id") + "', '" + jQuery(this).attr("name") + "');\">Update</a></span>"));
        className = (className === "uneven") ? "even" : "uneven";
    });
}

function updateContentType(contentTypeId, contentTypeName) {
    jQuery("a#" + contentTypeId + "").replaceWith("<img id=\"" + contentTypeId + "\" src=\"img/loading.gif\" alt=\"loading\" />");

    try {
        var webs = getAllSubWebs();

        webs.each(function () {
            var webUrl = jQuery(this).attr("Url");
            var lists = getListCollection(webUrl);
        
            lists.each(function () {
                var listName = jQuery(this).attr("Title");
                var contenttypefields = getContentTypeFields(contentTypeId, webUrl);
                var listContentTypes = getListContentTypes(contentTypeName, webUrl, listName);

                listContentTypes.each(function () {
                    var fieldsToAdd = getListContentTypeFields(jQuery(this).attr("id"), contenttypefields, webUrl, listName);
                    updateListContentType(jQuery(this).attr("id"), fieldsToAdd.wrapAll('<div></div>').parent().html(), webUrl, listName);
                });
            });
        });
        jQuery("img#" + contentTypeId + "").replaceWith("<img id=\"" + contentTypeId + "\" src=\"img/ok.png\" alt=\"ok\" />");
    }
    catch (error) {
        jQuery("img#" + contentTypeId + "").replaceWith("<img id=\"" + contentTypeId + "\" src=\"img/error.png\" alt=\"error\" />");
        alert("An error has occured while updating the content type:\n\n" + error.message);
    }
}

function getContentTypeFields(contentTypeId, webUrl) {
    var data;
    jQuery().SPServices({
        operation: "GetContentType",
        webURL: webUrl,
        contentTypeId: contentTypeId,
        async: false,
        completefunc:
            function (xData, Status) {
                data = jQuery(xData.responseText).find("fields");
            }
    });
    return data;
}

function getListContentTypes(contentTypeName, webUrl, listName) {
    var data;
    jQuery().SPServices({
        operation: "GetListContentTypes",
        webURL: webUrl,
        listName: listName,
        async: false,
        completefunc:
            function (xData, Status) {
                data = jQuery(xData.responseText).find("[Name='" + contentTypeName + "']");
            }
    });
    return data;
}

function getListContentTypeFields(contentTypeId, contenttypefields, webUrl, listName) {
    var fieldsToAdd = jQuery('<Fields></Fields>');
    jQuery().SPServices({
        operation: "GetListContentType",
        listName: listName,
        webURL: webUrl,
        contentTypeId: contentTypeId,
        async: false,
        completefunc:
            function (xData, Status) {
                var id = 0;
                var listcontenttypefields = jQuery(xData.responseText).find("fields");
                contenttypefields.children().each(function () {
                    var currentId = jQuery(this).attr("id");
                    var contains = false;
                    listcontenttypefields.children().each(function () {
                        if (jQuery(this).attr("id") === currentId) {
                            contains = true;
                        }
                    });
                    if (!contains) {
                        id++;
                        var fieldRefId = jQuery(this).attr("id");
                        var fieldRef = jQuery('<FieldRef></FieldRef').attr("id", fieldRefId);
                        var wrappedHtml = (jQuery(this).wrap("<Method ID='" + id + "' Cmd='New'></Method>"));
                        fieldsToAdd.append(wrappedHtml.parent());
                    }
                });
            }
    });
    return fieldsToAdd;
}

function updateListContentType(contentTypeId, fieldsToAdd, webUrl, listName) {
    fieldsToAdd = fieldsToAdd
        .replace(/<method/g, '<Method')
        .replace(/<\/method/g, '</Method')
        .replace(/<field/g, '<Field')
        .replace(/<\/field/g, '</Field')
        .replace(/id="/g, 'ID="');
    console.log("Using the following fields: %f", fieldsToAdd);
    jQuery().SPServices({
        operation: "UpdateContentType",
        listName: listName,
        webURL: webUrl,
        contentTypeId: contentTypeId,
        newFields: fieldsToAdd,
        addToView: "TRUE",
        async: false,
        completefunc:
            function (xData, Status) {
                console.log(xData.responseText);
            }
    });
}

function getAllSubWebs() {
    var data;
    jQuery().SPServices({
        operation: "GetAllSubWebCollection",
        async: false,
        completefunc:
            function (xData, Status) {
                data = jQuery(xData.responseText).find('Web');
            }
    });
    return data;
}

function getListCollection(webUrl) {
    var data;
    jQuery().SPServices({
        operation: "GetListCollection",
        webURL: webUrl,
        async: false,
        completefunc:
            function (xData, Status) {
                data = jQuery(xData.responseText).find('List');
            }
    });
    return data;
}